package org.elec.mac.inter;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.elec.mac.entity.SClientWxExtend;
import org.elec.mac.entity.SPrize;
import org.elec.mac.exception.ErrorCode;
import org.elec.mac.exception.ErrorMsg;
import org.elec.mac.service.SClientWxExtendService;
import org.elec.mac.service.SPrizeService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by wangtao on 2018/6/16.
 */
@Slf4j
@Controller
@RequestMapping(value = "/rev")
public class PrizeController {

    @Value("${annex.image.url}")
    private String imageurl;

    @Autowired
    private SClientWxExtendService sClientWxExtendService;

    @Autowired
    private SPrizeService sPrizeService;

    /**
     * 中奖
     *
     * @param request
     * @param response
     * @param openid
     * @param machid
     * @param orderid
     * @return
     * @throws IOException
     */
    @RequestMapping("/prize.do")
    private void prizeHandler(HttpServletRequest request, HttpServletResponse response,
                                @RequestParam(value = "openid", required = false) String openid,
                                @RequestParam(value = "machid", required = false) String machid,
                                @RequestParam(value = "orderid", required = false) String orderid) throws IOException {
        JSONObject json = new JSONObject();

        if (StringUtils.isBlank(openid)) {
            json.put("code", ErrorCode.ERR_NO_OPENID)
                    .put("msg", ErrorMsg.errorMessage(ErrorCode.ERR_NO_OPENID));

            response.getWriter().write(json.toString());
            return;
        }

        //原始奖品列表
        List<SPrize> orginalPrizeList = sPrizeService.list(null);
        for (SPrize sPrize : orginalPrizeList) {
            sPrize.setPicturePath(imageurl+sPrize.getPicturePath());
        }
        List<SPrize> zeroList = orginalPrizeList.stream().filter(sPrize -> sPrize.getSection() == 0).collect(Collectors.toList());

        assert zeroList.size() == 1;

        //谢谢惠顾所对应的Sprize
        SPrize zeroPrize = zeroList.get(0);

        Map<String, Object> param = new HashMap<>();
        param.put("openid", openid);

        SClientWxExtend sClientWxExtend = sClientWxExtendService.get(param);
        if(sClientWxExtend == null) {
            sClientWxExtend = new SClientWxExtend();
            sClientWxExtend.setOrdercount(0);
        }

        //下单次数
        int count = sClientWxExtend.getOrdercount();

        //中奖
        SPrize sPrize = luckDraw(count, orginalPrizeList, zeroPrize);
        log.info(""+sPrize);
        //最终奖品列表
        List<SPrize> finalPrizeList = getPricesList(sPrize, zeroPrize, 12, orginalPrizeList);
        log.info(""+finalPrizeList);
        JSONObject body = new JSONObject();

        json.put("code", ErrorCode.SUCCESS);
        json.put("msg",ErrorMsg.errorMessage(ErrorCode.SUCCESS));
        body.put("sPrize", new JSONObject(sPrize));
        body.put("finalPrizeList", finalPrizeList);
        json.put("body",body);
        log.info(json.toString());
        response.getWriter().write(json.toString());
    }

    /**
     * 抽奖
     *
     * @param count            抽奖次数
     * @param orginalPrizeList 原始抽奖列表
     * @param zeroPrize        谢谢惠顾
     * @return 最终用户所获取的奖品
     */
    private SPrize luckDraw(int count, List<SPrize> orginalPrizeList, SPrize zeroPrize) {

        SPrize finalPrize = zeroPrize;

        //奖池列表
        List<SPrize> prizes = null;

        if (count <= 3) {
            prizes = orginalPrizeList.stream()
                    .filter(sPrize -> sPrize.getSection() == 2 || sPrize.getSection() == 4)
                    .collect(Collectors.toList());
        } else if (count <= 6) {
            prizes = orginalPrizeList.stream()
                    .filter(sPrize -> sPrize.getSection() == 2 || sPrize.getSection() == 4 || sPrize.getSection() == 3)
                    .collect(Collectors.toList());
        } else {
            prizes = orginalPrizeList;
        }

        //随机数
        int ran = (int) (Math.random() * 100);

        for (SPrize prize : prizes) {
            if (ran == prize.getId()) {
                finalPrize = prize;
                break;
            }
        }

        int prizeNo = finalPrize.getSection();

        String msg = prizeNo == 0 ? "没中奖" : "中奖了";
        log.info(msg + " result : " + prizeNo);

        return finalPrize;
    }

    /**
     * 获取最终奖品列表
     *
     * @param prize     奖品
     * @param zeroPrize 谢谢惠顾
     * @param size      列表长度
     * @param sPrizes   原始抽奖列表
     * @return 最终奖品列表
     */
    private List<SPrize> getPricesList(SPrize prize, SPrize zeroPrize, int size, List<SPrize> sPrizes) {

        if (sPrizes.remove(zeroPrize) && size > sPrizes.size()) {
            throw new IndexOutOfBoundsException("列表大小不能超过奖池大小 size : " + size + " currentSize : " + sPrizes.size());
        }

        List<SPrize> finalList = new ArrayList<>();

        //添加谢谢惠顾进列表
        finalList.add(zeroPrize);

        if (prize.getSection() != 0) {
            //把中奖号从奖池中移除并放在最终列表中
            sPrizes.remove(prize);
            finalList.add(prize);
        }

        List<SPrize> firstPrizeNos = sPrizes.stream()
                .filter(sPrize -> sPrize.getSection() == 1)
                .collect(Collectors.toList());

        List<SPrize> secondPrizeNos = sPrizes.stream()
                .filter(sPrize -> sPrize.getSection() == 2)
                .collect(Collectors.toList());

        List<SPrize> thirdPrizeNos = sPrizes.stream()
                .filter(sPrize -> sPrize.getSection() == 3)
                .collect(Collectors.toList());

        List<SPrize> fourthPrizeNos = sPrizes.stream()
                .filter(sPrize -> sPrize.getSection() == 4)
                .collect(Collectors.toList());

        addList(sPrizes, finalList, firstPrizeNos, size);
        addList(sPrizes, finalList, secondPrizeNos, size);
        addList(sPrizes, finalList, thirdPrizeNos, size);
        addList(sPrizes, finalList, fourthPrizeNos, size);

        while (finalList.size() != size) {
            finalList.add(sPrizes.remove(new Random().nextInt(sPrizes.size())));
        }

        return finalList;
    }

    private void addList(List<SPrize> orginalList, List<SPrize> finalList, List<SPrize> intervalPrizes, int size) {
        if (finalList.size() != size && intervalPrizes.size() != 0) {
            SPrize removePrize = intervalPrizes.remove(new Random().nextInt(intervalPrizes.size()));
            finalList.add(removePrize);
            orginalList.remove(removePrize);
        }
    }


//    @Test
//    public void test() {
//        List<SPrize> sPrizes = new ArrayList<>();
//
//        sPrizes.add(new SPrize(1, 4));
//        sPrizes.add(new SPrize(2, 4));
//        sPrizes.add(new SPrize(3, 4));
//        sPrizes.add(new SPrize(4, 4));
//        sPrizes.add(new SPrize(5, 3));
//        sPrizes.add(new SPrize(6, 3));
//        sPrizes.add(new SPrize(7, 3));
//        sPrizes.add(new SPrize(8, 3));
//        sPrizes.add(new SPrize(9, 3));
//        sPrizes.add(new SPrize(10, 4));
//        sPrizes.add(new SPrize(11, 4));
//        sPrizes.add(new SPrize(12, 2));
//        sPrizes.add(new SPrize(13, 2));
//        sPrizes.add(new SPrize(14, 2));
//        sPrizes.add(new SPrize(15, 2));
//        sPrizes.add(new SPrize(16, 1));
//        sPrizes.add(new SPrize(17, 0));
//
//
//        List<SPrize> zeroList = sPrizes.stream().filter(sPrize -> sPrize.getSection() == 0).collect(Collectors.toList());
//
//        assert zeroList.size() == 1;
//
//        //谢谢惠顾
//        SPrize zeroPrize = zeroList.get(0);
//
//        //中奖奖品
//        SPrize finalPrize = luckDraw(10, sPrizes, zeroPrize);
//
//        //最终中奖列表
//        List<SPrize> finalPrizeList = getPricesList(finalPrize, zeroPrize, 12, sPrizes);
//
//        System.out.println(finalPrize);
//        System.out.println(finalPrizeList);
//
//        finalPrizeList.forEach(prize -> System.out.println(prize.getId()));
//
//        List<Integer> integers = new ArrayList<>();
//        integers.add(0);
//        integers.add(1);
//        integers.add(2);
//        integers.add(3);
//        integers.add(4);
//        for (SPrize s : finalPrizeList) {
//            integers.remove(s.getSection());
//        }
//
//        if (integers.size() == 0) {
//            System.out.println("ok！");
//        } else {
//            System.out.println(integers);
//            System.out.println("fail！");
//        }
//
//    }
}
